<template>
<myLeftRightLaout>
  <template v-slot:leftL>
    <myList height="100%" width="100%" @listToggle="showContend" :listData="writeConfig"></myList>
  </template>
  <template v-slot:rightL>
  <div style="width: 100%;">
    <div> 代码</div>
      <textarea id="textArea" 
      style="height: 300px;" cols="5" rows="5" 
      :value ="((currentItem.contend as writeCodeModel).code)"/>
      <button @click="run"> run </button>
      <div> 描述：</div>
      <pre>{{ (currentItem.contend as writeCodeModel).desc }}</pre>
  </div>
  </template>
</myLeftRightLaout>
</template>

<script setup lang="ts">
import myLeftRightLaout from '@/components/myLeftRightLaout/index.vue'
import useHttp from '@/utils/http/http';
import { ref, reactive, onMounted } from 'vue'
import myList from '@/components/myList/index.vue'
import {writeCodeModel} from '@/model/writeCodeModel.ts'

let writeConfig = ref({})
async function init(){
  writeConfig.value = await useHttp('writeCode')
  console.log(writeConfig.value);
  
}
init()

onMounted(() => {
const text = document.querySelector("#textArea") as HTMLElement
  const fn = () => {
    console.log('scroll');
  }
  const test = throttled(fn)
  const test2 = throttled2(fn)

  text.addEventListener('scroll', () => {
    test()
    test2()
  })
})
// eslint-disable-next-line no-undef
type Timer = NodeJS.Timeout | null 
const throttled = (fn: () => void, timing = 100) => {
  let timer: Timer = null
  // eslint-disable-next-line no-undef
  return function ():void | NodeJS.Timeout {
    if (!timer) {
      timer = setTimeout(() => {
        fn()
        timer = null
      }, timing);
    }
  }
}
const throttled2 = (fn:() => void) => {
  let oldTime = Date.now()

  return function () {
    let nowTime = Date.now()
    const time = nowTime - oldTime
    if (time > 200) {
      fn()
      oldTime = nowTime
    }
  }
}
type currentType = {
  contend:writeCodeModel  | []
}
const currentItem = reactive<currentType>({
  contend: []
})
const debounce = (timing = 200) => {
  // eslint-disable-next-line no-undef
  let timer: boolean | NodeJS.Timeout  = false
  return function (fn:()=>void) {
    // eslint-disable-next-line no-undef
    clearTimeout(timer as NodeJS.Timeout )
    timer = setTimeout(() => {
      fn()
      timer = true
    }, timing)
  }
}
const test1 = debounce()
const run = () => {
  const fn = () => {
    console.log('Click');
  }
  test1(fn)
}

const showContend = (params:writeCodeModel) => {
  currentItem.contend = params
}
</script>
<style scoped>

</style>